package com.caigou.comm.base.network

import com.caigou.comm.base.constants.HttpConstant
import com.caigou.comm.base.container.BaseApplication
import com.caigou.comm.base.network.interceptors.HeadersInterceptor
import com.caigou.comm.base.network.interceptors.LoggingInterceptor
import com.google.gson.GsonBuilder
import okhttp3.Cache
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.io.File
import java.util.concurrent.TimeUnit

/**
 * @author #Suyghur.
 * Created on 2021/09/13
 */
object ServiceCreators {

    private const val BASIC_URL = "https://8888188t.com"

    private val cacheFile = File(BaseApplication.getContext().cacheDir, "cache")
    private val cache = Cache(cacheFile, HttpConstant.MAX_CACHE_SIZE)

    val httpClient = OkHttpClient.Builder()
        .connectTimeout(10, TimeUnit.SECONDS)
        .readTimeout(10, TimeUnit.SECONDS)
        .writeTimeout(20, TimeUnit.SECONDS)
//        .addInterceptor(MultiBaseUrlInterceptor())
        .addInterceptor(LoggingInterceptor())
        .addInterceptor(HeadersInterceptor())
        .cache(cache)
//        .addInterceptor(BasicParamsInterceptor())
        .build()

    private val builder = Retrofit.Builder()
        .baseUrl(BASIC_URL)
        .client(httpClient)
        .addCallAdapterFactory(FlowCallAdapterFactory.create())
        .addConverterFactory(GsonConverterFactory.create(GsonBuilder().registerTypeAdapterFactory(GsonTypeAdapterFactory()).create()))

    private val retrofit = builder.build()

    fun <T> create(serviceClz: Class<T>): T = retrofit.create(serviceClz)
}